//
//  CMDBApplicationManager.swift
//  CMDB
//
//  Created by 王磊 on 17/4/5.
//  Copyright © 2017年 CMDB. All rights reserved.
//

import UIKit

class CMDBApplicationManager: NSObject {
    
    static let getInstance: CMDBApplicationManager = CMDBApplicationManager()
    
    private override init() {
        super.init()
        
    }
    
    internal var account: CMDBAccountBean?
    
    internal var token: String = ""
    
}

// MARK: 校验token
class CMDBCheckTokenParam: CMDBBasicParamBean {
    
    
}
extension CMDBCheckTokenParam {
    
    override func URLString() -> String {
        
        return CMDB_Http_Formal_Domain + "/app/account/\(server_Version)/checkToken?"
    }
}

extension CMDBApplicationManager {
    
    func checkToken(errorHandler: CMDBHttpErrorHandler) {
        
        let param = CMDBCheckTokenParam()
        
        if token.isEmpty {
            
            errorHandler(rescode: CMDBRescodeType.Mutex)
            
            return
        }
        
        CMDBHttpManager.getInstance.request(param.URLString(), param: param.keyValues, success: { (sysTime, data, page) in
            
            }, error: { (rescode) in
                
                errorHandler(rescode: rescode)
        }) {
            
            
        }
    }
}


extension CMDBApplicationManager: CMDBApplicationManagerDelegate {
    
    func saveAccount(account: CMDBAccountBean?) {
        guard let tempAccount = account else {
            
            return
        }
        
        CMDBUserDefault.setObject(tempAccount.token, forKey: "token")
        
        CMDBUserDefault.setObject(tempAccount.phone, forKey: "phone")
        
        CMDBUserDefault.setObject(tempAccount.uid, forKey: "uid")
        
        CMDBUserDefault.setObject(tempAccount.associate, forKey: "associate")
        
        CMDBUserDefault.setObject(tempAccount.icon, forKey: "icon")
        
        CMDBUserDefault.synchronize()
        
        token = tempAccount.token
        
        self.account = tempAccount
    }
    func queryAccount() -> CMDBAccountBean? {
        
        guard let tempToken = CMDBUserDefault.objectForKey("token") else {
            
            return nil
        }
        let tempUid = CMDBUserDefault.objectForKey("uid")
        
        let tempIcon = CMDBUserDefault.objectForKey("icon")
        
        let account = CMDBAccountBean()
        
        account.token = tempToken as! String
        
        account.icon  = (tempIcon ?? "") as! String
        
        account.uid = tempUid as! String
        
        account.associate = CMDBUserDefault.objectForKey("associate") as! String
        
        self.account = account
        
        self.token = tempToken as! String
        
        return account
    }
    
    func querryToken() -> String {
        
        guard let tempToken = CMDBUserDefault.objectForKey("token") else {
            
            return ""
        }
        
        return tempToken as! String
        
    }
    
    func clearAccount() {
        
        guard token.isEmpty else {
            
            return
        }
        CMDBUserDefault.removeObjectForKey("token")
        
        CMDBUserDefault.removeObjectForKey("uid")
        
        CMDBUserDefault.removeObjectForKey("associate")
        
        token = ""
        
        account = nil
    }
}
extension CMDBApplicationManager {
    
    func isLatestVersion() -> Bool {
        
        let url = NSURL(string: checkUrlDomain)
        
        do {
            
            let appInfoString = try? NSString(contentsOfURL: url!, encoding: NSUTF8StringEncoding)
            
            guard let _ = appInfoString else {
                
                return false
            }
            
            guard let jsonData = appInfoString!.dataUsingEncoding(NSUTF8StringEncoding) else {
                
                return false
            }
            let appInfo: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableLeaves) as! NSDictionary
            
            let resultArray = appInfo["results"] as! NSArray
            
            
            guard let resultsDict = resultArray.firstObject else {
                
                return false
            }
//            let version = resultsDict!["version"]
            
            let version = resultsDict["version"] as! String
            
            return compare(version)
        } catch {
            
            printLog(error)
            
            return false
        }
    }
    private func compare(serviceVersion: String) -> Bool {
        
        let infoDic: NSDictionary = NSBundle.mainBundle().infoDictionary!
        
        let appVersion = infoDic.objectForKey("CFBundleShortVersionString") as! String
        
        return appVersion.compare(serviceVersion, options: NSStringCompareOptions.NumericSearch) == .OrderedAscending
    }
}


extension CMDBApplicationManager {
    
    func openAppStore() {
        
        UIApplication.sharedApplication().openURL(NSURL(string: appStoreDomain)!)
        
    }
}
// MARK: 本地版本
extension CMDBApplicationManager {
    
    var localVersion: String {
        
        let infoDic: NSDictionary = NSBundle.mainBundle().infoDictionary!
        
        let localVersion = infoDic.objectForKey("CFBundleShortVersionString") as! String
        
        return localVersion
    }
}
// MARK: 9位appid
extension CMDBApplicationManager {
    
    var appId: String {
        
        return "123456789"
    }
}
// MARK:
extension CMDBApplicationManager {
    var appStoreDomain: String {
        
        return "itms-apps://itunes.apple.com/app/id\(appId)"
    }
}
// MARK: 检测
extension CMDBApplicationManager {
    
    var checkUrlDomain: String {
        
        return "https://itunes.apple.com/lookup?id=\(appId)"
    }
}
// MARK: 打开评论
extension CMDBApplicationManager {
    
    var appStoreCommentDomain: String {
        
        return "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=\(appId)&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8"
    }
    func openAppStoreComment() {
        
        UIApplication.sharedApplication().openURL(NSURL(string: appStoreCommentDomain)!)
    }
}


extension CMDBApplicationManager {
    
    func lanuchScreenShow(vc: UIViewController) {
        
        let launchScreenView = CMDBLaunchScreenView.launchScreenView()
        
        vc.view.addSubview(launchScreenView)
        
        launchScreenView.updateImage(UIImage(named: "logo"))
        
        launchScreenView.performSelector(#selector(launchScreenView.dismiss), withObject: nil, afterDelay: 1)
    }
}
